<?php

namespace App\Http\Controllers\Article;

use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UnlockController extends BaseController
{
    public function points()
    {
        $user_id = auth('api')->id();
        $unlock_points = DB::table('users')
            ->join('user_titles','users.user_title_id','=','user_titles.id')
            ->where('users.id',$user_id)
            ->value('user_titles.unlock_points');


        return $this->success(['unlock_points' => $unlock_points]);
    }


    public function check(Request $request)
    {
        $params = $this->validate($request,[
            'article_id' =>  'required|integer'
        ]);

        $params['user_id'] = auth('api')->id();
        $is_unlock =  DB::table('user_unlock_articles')->where($params)->exists();

        return $this->success([
            'is_unlock' => $is_unlock
        ]);
    }


    public function index(Request $request)
    {
        $params = $this->validate($request,[
            'article_id' =>  'required|integer'
        ]);

        $user_id = auth('api')->id();

        $user = DB::table('users')
                            ->select(['user_titles.unlock_points','users.points'])
                            ->join('user_titles','users.user_title_id','=','user_titles.id')
                            ->where('users.id',$user_id)
                            ->first();

        if ($user->points<$user->unlock_points){
            return $this->error('对不起您的积分不足');
        }
        $datetime = date('Y-m-d H:i:s');
        $result = DB::table('user_unlock_articles')
            ->insert([
                'user_id' => $user_id,
                'article_id' => $params['article_id'],
                'unlock_time' => $datetime
            ]);

        if ($user->unlock_points>0){
            DB::table('users')->where('id',$user_id)->decrement('points',$user->unlock_points);

            DB::table('user_points_details')
                ->insert([
                    'user_id' => $user_id,
                    'change_type'=> 2,
                    'points' => $user->unlock_points,
                    'remark' => '解锁管理宝典扣除',
                    'change_time' => $datetime
                ]);

        }
        return  $result ? $this->success('解锁成功') : $this->error('解锁失败');


    }
}
